package ru.ifmo.filemanager.local;

import static java.io.File.listRoots;
import static ru.ifmo.filemanager.async.Async.execute;
import static ru.ifmo.filemanager.filesystem.FileSystem.deregisterRoot;
import static ru.ifmo.filemanager.filesystem.FileSystem.registerRoot;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import ru.ifmo.filemanager.filesystem.FileSystem;
import ru.ifmo.filemanager.filesystem.interfaces.FileSystemObject;
import ru.ifmo.filemanager.local.FileLister;

public class Plugin {

	private Plugin() { }
	
	static FileSystemObject wrap(File file) {
		if (!file.exists()) {
			return null;
		}
		if (file.isFile()) {
			return new LocalFile(file);
		}
		if (file.isDirectory()) {
			return new LocalDirectory(file);
		}
		return new LocalUnknown();
	}
	
	static List<String> roots = new ArrayList<String>();
	
	static Runnable refreshRoots = new Runnable() {
		
		public void run() {
			synchronized (roots) {
				for (String root: roots) {
					deregisterRoot(root);
				}
				for (File root: listRoots()) {
					FileSystemObject wrapped = wrap(root);
					if (wrapped != null) {
						String path = root.getPath();
						if (registerRoot(path, wrapped)) {
							roots.add(path);
						}
					}
				}
			}
			FileSystem.refreshRoots();
		}
	};
	
	public static void load() {		
		execute(refreshRoots);
		
		FileLister.initLister();
	}
}